package com.alinesno.cloud.common.web.base.exceptions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alinesno.cloud.common.facade.response.ResponseBean;
import com.alinesno.cloud.common.web.login.auth.UnauthorizedOperationException;

/**
 * springboot全局异常处理
 * 
 * @author WeiXiaoJin
 * @since 2019年2月8日 下午2:24:05
 */
@ControllerAdvice
public class WebExceptionHandler {
	

	@SuppressWarnings("unused")
	private static final Logger log = LoggerFactory.getLogger(WebExceptionHandler.class);

	/**
	 * 权限认证拦截
	 * @param req
	 * @param e
	 * @return
	 * @throws Exception
	 */
	@ExceptionHandler(value= {UnauthorizedException.class , UnauthorizedOperationException.class})
    @ResponseBody
    public ResponseBean defaultExceptionHandler(HttpServletRequest request , HttpServletResponse response , Exception e){
		ResponseBean rb = WebExceptionUtils.handleAuthException(e,request); 
		return WebExceptionUtils.errorRedirect(rb, request, response); 
    }
	
	/**
	 * 前端参数异常
	 * @param e
	 * @param result
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@ExceptionHandler(value = {BindException.class , NullPointerException.class})
	public ResponseBean illegalArgumentException(Exception e , BindingResult result , HttpServletRequest request , HttpServletResponse response) throws Exception {
		ResponseBean rb = WebExceptionUtils.handleException(e, result , request); 
		return WebExceptionUtils.errorRedirect(rb, request, response); 
	}

	
}